package system

import (
	"errors"
	"ltbz/cultural_tourism_api/models/system"
	"ltbz/cultural_tourism_api/utils"
	"strconv"
	"time"
)

func Login(adminName, password string) (ret system.LoginResp, err error, errMsg string) {
	//查询管理员账号是否存在
	sysUserObj := new(system.SysUser)
	sysUserInfo, err := sysUserObj.GetSysUserByUserName(adminName)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "登录失败,账号错误"
			err = errors.New(errMsg + "Err:" + err.Error())
			return
		}
		errMsg = "登录失败,查询账号出错"
		err = errors.New(errMsg + "Err:" + err.Error())
		return
	}
	password = utils.MD5(password + utils.PwdPrefix)
	//查询密码是否匹配
	if sysUserInfo.Password != password {
		errMsg = "登录失败,密码错误"
		err = errors.New(errMsg)
		return
	}
	//查询账号是否有效
	if sysUserInfo.Enabled == 0 {
		errMsg = "您的账号已被禁用，如需登录，请联系管理员"
		err = errors.New(errMsg + "已禁用账号：" + sysUserInfo.SysUserName + " " + sysUserInfo.RealName)
		return
	}
	//生成token
	token := utils.GenToken(strconv.Itoa(int(sysUserInfo.SysUserId)) + sysUserInfo.SysUserName)
	if err != nil {
		errMsg = "登录失败,生成token出错"
		err = errors.New(errMsg + "Err:" + err.Error())
		return
	}

	//更新用户的最新登录时间
	sysUserInfo.LastLoginTime = time.Now()
	sysUserInfo.Token = token

	whereParam := map[string]interface{}{"sys_user_id": sysUserInfo.SysUserId}
	updateParams := map[string]interface{}{"last_login_time": time.Now(), "token": token}
	err = sysUserObj.Update(updateParams, whereParam)
	if err != nil {
		errMsg = "更新登录信息失败"
		err = errors.New(errMsg + "Err:" + err.Error())
		return
	}
	ret.SysUserName = sysUserInfo.SysUserName
	ret.RealName = sysUserInfo.RealName
	ret.SysUserId = sysUserInfo.SysUserId
	ret.Token = token
	if password == utils.DefaultPwd {
		ret.ChangePwd = true
	}
	return
}
